
var isFirefox = navigator.userAgent.indexOf('Firefox') !== -1 || navigator.userAgent.indexOf('Gecko/') !== -1;
let countPassword=0;
let countUsername=0;
let passwordIndex=0;

let passwordEl = null;
let usernameEl = null;

let formEl = document;

const theurl = document.location.origin;
//let theurl = document.location.href;




//init();

// chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
//     theurl = tabs[0].url;
//     // use `url` here inside the callback because it's asynchronous!
// });

//content_scripts——>background发送消息
/* chrome.runtime.sendMessage({type:'getAccount'},function(response) {
	var data = response.data;
	var pmapStr = window.localStorage.pmap;
	if(pmapStr&&pmapStr!=''){
		var pmap = eval('(' + pmapStr + ')');
		if(pmap&&pmap[theurl]){
			data = pmap[theurl];
		}
	}
    setPasswordFunc(data);
    setUsernameFunc(data);
	addPreSubmit();
}); */

chrome.runtime.sendMessage({type:'doPsw',theurl:theurl},function(response) {
	var doPsw = response.doPsw;
	if(doPsw){
		init();
	}
	
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if(request.type=="refresh"){
			document.location.reload();
        }
	});

function init(){
	var data = {username:'',password:''};
	// var pmapStr = window.localStorage.pmap;
	
	chrome.runtime.sendMessage({type:'getPsw'},function(response) {
		var pmapStr = response.pmapStr;
		if(pmapStr&&pmapStr!=''){
			var dec = decrypts(pmapStr);
			var pmap = eval('(' + dec + ')');
			if(pmap&&pmap[theurl]){
				data = pmap[theurl];
			}
		}
		setFormFunc();
		setPasswordFunc(data);
		setUsernameFunc(data);
		addPreSubmit();
		
	});
	
	
};

function setFormFunc(){
	if(theurl == 'https://10.240.1.45'){
		formEl = document.querySelector('form[data-tab="sms"]');
	}
}

function setPasswordFunc({username,password}){
	var abc = $('input[type=password]');
    if(formEl.querySelector('input[type=password]')){
		var inputs = formEl.querySelectorAll('input');
		for(var index=0;index<inputs.length;index++){
			var item = inputs.item(index);
			if(item.type=='password'&&!item.readOnly&&item.value==''){
			    //setValueForElement(item);
			    item.value=password;
			    //setValueForElementByEvent(item);
				passwordIndex=index;
				passwordEl=item;
				break;
			}
		}
    }else{
        if(countPassword<20){
            setTimeout(()=>{
                countPassword++;
                setPasswordFunc({username,password})
            },1000)
        }
    }
}

function setUsernameFunc({username,password}){

    let usernameEle=null;
	
	var inputs = formEl.querySelectorAll('input');
	for(var index=0;index<inputs.length;index++){
		var item = inputs.item(index);
		if(index<passwordIndex){
		    if(item.type === 'text' || item.type === 'email' || item.type === 'tel') {
		        usernameEle=item;
		        break;
		    }
		}
	}

    if(usernameEle&&!usernameEle.readOnly){
        //setValueForElement(usernameEle);
        usernameEle.value=username;
		usernameEl=usernameEle;
        //setValueForElementByEvent(usernameEle);
    }else{
        if(countUsername<20){
            setTimeout(()=>{
                countUsername++;
                setUsernameFunc({username,password})
            },1000)
        }
    }
}

function addPreSubmit(){
	var pss = $('input[type=password]');
	var theform = pss.parents('form');
	theform.submit(beforeSubmit);
/* 	var options={
	//target:'#output1',  //把服务器返回内容放入id为output1的元素中
	beforeSubmit:beforeSubmit //提交前的回调函数
	//success:showResponse,  //提交后的回调函数
	//url:url,   //默认是form的action,如果申明，则会覆盖
	//type:type,   //默认是form的method('get' or 'post'),如果申明，则会覆盖
	//dateType:null,  //'xml','script',or 'json'(接受服务端返回的类型)
	//clearForm:true,  //成功提交后，清除所有表单元素的值
	//resetForm:true,  //成功提交后，重置所有表单的值
	//timeout:3000   //限制请求的时间，当请求大于3秒后，跳出请求
	} */
	// theform.ajaxForm(options);
}

function beforeSubmit(){
	// var pmap = {};
	var data = {
				username:usernameEl.value,
				password:passwordEl.value
				};
	chrome.runtime.sendMessage({type:'setPsw',theurl:theurl,data:data});
	
}
/*
function beforeSubmit(){
	// var pmap = {};
	chrome.runtime.sendMessage({type:'getPsw'},function(response) {
		var pmapStr = response.pmapStr;
		var pmap = {};
		if(pmapStr&&pmapStr!=''){
			var dec = decrypts(pmapStr);
			pmap = eval('(' + dec + ')');
			if(!pmap){
				pmap = {};
			}
			pmap[theurl] = {
				username:usernameEl.value,
				password:passwordEl.value
			};
			// window.localStorage.pmap = encrypts(JSON.stringify(pmap));
			pmapStr = encrypts(JSON.stringify(pmap));
			chrome.runtime.sendMessage({type:'setPsw',pmapStr:pmapStr},function(response) {
			});
			
		}
		
	});
	
}
*/

// // set value of the given element
// function setValueForElement(el) {
//     var valueToSet = el.value;
//     // clickElement(el);
//     // doFocusElement(el, false);
//     el.dispatchEvent(normalizeEvent(el, 'keydown'));
//     el.dispatchEvent(normalizeEvent(el, 'keypress'));
//     el.dispatchEvent(normalizeEvent(el, 'keyup'));
//     el.value !== valueToSet && (el.value = valueToSet);
// }

// // set value of the given element by using events
// function setValueForElementByEvent(el) {
//     var valueToSet = el.value,
//         ev1 = el.ownerDocument.createEvent('HTMLEvents'),
//         ev2 = el.ownerDocument.createEvent('HTMLEvents');

//     el.dispatchEvent(normalizeEvent(el, 'keydown'));
//     el.dispatchEvent(normalizeEvent(el, 'keypress'));
//     el.dispatchEvent(normalizeEvent(el, 'keyup'));
//     ev2.initEvent('input', true, true);
//     el.dispatchEvent(ev2);
//     ev1.initEvent('change', true, true);
//     el.dispatchEvent(ev1);
//     el.blur();
//     el.value !== valueToSet && (el.value = valueToSet);
// }

// // normalize the event since firefox handles events differently than others
// function normalizeEvent(el, eventName) {
//     var ev;
//     if (isFirefox) {
//         ev = document.createEvent('KeyboardEvent');
//         ev.initKeyEvent(eventName, true, false, null, false, false, false, false, 0, 0);
//     }else {
//         ev = el.ownerDocument.createEvent('Events');
//         ev.initEvent(eventName, true, false);
//         ev.charCode = 0;
//         ev.keyCode = 0;
//         ev.which = 0;
//         ev.srcElement = el;
//         ev.target = el;
//     }

//     return ev;
// }



